package com.tianheng.wanzhou.datacollecting.netty.cushaji;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianheng.wanzhou.datacollecting.db.entity.Cushaji;
import com.tianheng.wanzhou.datacollecting.db.entity.MachineList;
import com.tianheng.wanzhou.datacollecting.db.service.ICushajiService;
import com.tianheng.wanzhou.datacollecting.db.service.IMachineListService;
import com.tianheng.wanzhou.datacollecting.util.FloatOperate;
import com.tianheng.wanzhou.datacollecting.util.SerializeUtil;
import com.tianheng.wanzhou.datacollecting.util.StrUtil;
import com.tianheng.wanzhou.datacollecting.util.TqlHexchange;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:
 * @Date: 2020/5/12 14:26
 * @Version 1.0
 */
@Slf4j
@Component(value = "cushajiHandler")
@Scope("prototype")
public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    ICushajiService cushajiService;
    @Autowired
    IMachineListService machineListService;
    private List<MachineList> machineList = new ArrayList<>();

//    @Resource
//    Jedis jedis;

    private static ClientHandler clientHandler;

    @PostConstruct
    public void init() {
        clientHandler = this;
        cushajiService = this.cushajiService;
//        jedis = this.jedis;
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 6).eq("status", 1);
        machineList = machineListService.list(queryWrapper);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接服务端" + clientIP + "成功!");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
//        MachineList machine = (MachineList) SerializeUtil.deserialize(jedis.get(clientIP.getBytes()));
        try {
            MachineList machine = new MachineList();
            for (MachineList machine1 : this.machineList) {
                if(clientIP.equals(machine1.getMacIp())){
                    machine =machine1;
                    break;
                }
            }
            ByteBuf buf = (ByteBuf)msg;
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            String str = StrUtil.bytesToHexString(bytes);
            log.info("收到数据:" + str);
            Cushaji cushaji = new Cushaji();
            cushaji.setMachineIp(machine.getMacIp());
            cushaji.setMacId(machine.getMacId());
//            cushaji.setMachineIp(clientIP);
            String length = str.substring(4, 6).toLowerCase();
            String data = str.substring(6, str.length() - 4);
            if (length.equals("e8")) {
                cushaji.setYiFangShaLayer(StrUtil.hexStr2Int(data.substring(0,4)));
                cushaji.setYiFangShaLength(StrUtil.hexStr2Int(data.substring(16,20)));
                cushaji.setCurrentLocation(FloatOperate.decima3(data.substring(104,112)));
                cushaji.setTongshaDiameter(FloatOperate.decima3(data.substring(456,464)));
            }
            if (length.equals("96")){
                cushaji.setNianDu(Double.valueOf((TqlHexchange.zcInt(data.substring(0,4))))/1000);
                cushaji.setJingxiangParam2(StrUtil.hexStr2Int(data.substring(24,28)));
                cushaji.setJingxiangParam1(StrUtil.hexStr2Int(data.substring(32,36)));
                cushaji.setSetLength(StrUtil.hexStr2Int(data.substring(120,124)));
                cushaji.setInitialAdjustmentPosition(TqlHexchange.zcDouble(data.substring(136,144)));
                cushaji.setSpeedAddParam(StrUtil.hexStr2Int(data.substring(144,148)));
                cushaji.setSpeedReduceParam(StrUtil.hexStr2Int(data.substring(152,156)));
                cushaji.setDistanceOfCircle(StrUtil.hexStr2Int(data.substring(280,284))/10);
                cushaji.setLocationAdjustment1(TqlHexchange.zcDouble(data.substring(292,296)));
                cushaji.setLocationAdjustment2(TqlHexchange.zcDouble(data.substring(296,300)));
            }
            if (length.equals("b4")){
                cushaji.setLocationSpeed(StrUtil.hexStr2Int(data.substring(0,4)));
                cushaji.setLuoshaReverseTime(FloatOperate.decima4(data.substring(8,12)));
                cushaji.setTwineLuoshaTension(FloatOperate.decima4(data.substring(28,32)));
                cushaji.setClassAYield(StrUtil.reverseHex2Int(data.substring(248,256)).intValue());
                cushaji.setClassBYield(StrUtil.reverseHex2Int(data.substring(272,280)).intValue());
                cushaji.setClassCYield(StrUtil.reverseHex2Int(data.substring(296,304)).intValue());
                cushaji.setClassDYield(StrUtil.reverseHex2Int(data.substring(320,328)).intValue());
                cushaji.setClassAllYield(StrUtil.reverseHex2Int(data.substring(352,360)).intValue());
            }
            if (length.equals("7c")){
                cushaji.setSpindleSpeed(StrUtil.hexStr2Int(data.substring(0,4)));
                cushaji.setFrontLolaSpeed(StrUtil.hexStr2Int(data.substring(16,20)));
                cushaji.setTwineLocation(TqlHexchange.zcDouble(data.substring(24,32)));
                cushaji.setTwineTime(TqlHexchange.zcDouble(data.substring(132,136)));
            }
            if (length.equals("02")){
                cushaji.setAverageSpindleSpeed(TqlHexchange.zcInt(data.substring(0,4)));
            }
            if (length.equals("06")){
                cushaji.setYarnChangeNum(TqlHexchange.zcInt(data.substring(0,4)));
            }
            if (length.equals("04")){
                cushaji.setSetYarnChange(TqlHexchange.zcInt(data.substring(0,4)));
                cushaji.setDownDelay(TqlHexchange.zcDouble(data.substring(4,8)));
            }
            cushajiService.saveOrUpdate(cushaji);
            if (length.equals("04")){
                ctx.channel().close();
                ctx.close();
            }
        }finally {
            ReferenceCountUtil.release(msg);
        }

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("数据读取完毕");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接"+ clientIP +"移除");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生错误:" + cause.toString());
        ctx.close();
    }

}
